package com.lb.shopguide.ui.fragment.guide.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterGoodsInCheckout;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.goods.GoodsDetailBean;
import com.lb.shopguide.entity.order.CommitGoodsBean;
import com.lb.shopguide.entity.order.ConfirmOrderBean;
import com.lb.shopguide.event.guide.GiveupPayEvent;
import com.lb.shopguide.event.guide.GoHomeEvent;
import com.lb.shopguide.event.guide.PaySuccessEvent;
import com.lb.shopguide.event.guide.SearchBarcodeCheckoutEvent;
import com.lb.shopguide.event.guide.SelectGoodsSkuEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.activity.ScanSmallActivity;
import com.lb.shopguide.ui.dialog.DialogLbCommon;
import com.lb.shopguide.ui.dialog.DialogMakeSure;
import com.lb.shopguide.ui.fragment.guide.FragmentSearch;
import com.lb.shopguide.ui.fragment.guide.goods.FragmentSelectGoods;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizGoodsUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.ClickUtil;
import com.lb.shopguide.util.lb.MathDecimalUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/5/31.
 * 收银台
 */

public class FragmentCheckout extends BaseCommonFragment {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.layout_empty)
    RelativeLayout layoutEmpty;
    @BindView(R.id.layout_price_total)
    LinearLayout layoutPriceTotal;
    @BindView(R.id.layout_add_goods)
    LinearLayout layoutAddGoods;
    @BindView(R.id.layout_scan)
    LinearLayout layoutScan;
    @BindView(R.id.layout_action)
    LinearLayout layoutAction;
    @BindView(R.id.layout_real_bottom)
    RelativeLayout layoutRealBottom;
    @BindView(R.id.tv_price_total)
    TextView tvPriceTotal;
    @BindView(R.id.tv_do_order)
    TextView tvAction;
    @BindView(R.id.chk_all)
    CheckBox chkAll;

    private List<GoodsDetailBean> mGoodsInOrderList;
    private AdapterGoodsInCheckout mAdapterGoodsInCheckout;

    private boolean isEdit = false;

    private boolean flagToHome = false;

    private SearchBarcodeCheckoutEvent mEvent;

    public static FragmentCheckout newInstance() {
        FragmentCheckout fragment = new FragmentCheckout();
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_checkout;
    }

    @Override
    public void initData() {
        mGoodsInOrderList = new ArrayList<>();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setTitleText("收银台");
        ntb.setRightText("编辑");

//        mSwipeRefreshLayout.setOnRefreshListener(this);
//        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterGoodsInCheckout = new AdapterGoodsInCheckout(R.layout.item_goods_in_order, mGoodsInOrderList, AppConstant.GOODS_MODE_SHOW);
        mRecyclerView.setAdapter(mAdapterGoodsInCheckout);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).paintProvider(mAdapterGoodsInCheckout).build());
        checkIfEmpty();
        initListener();

        tvPriceTotal.setText("￥0");
        mAdapterGoodsInCheckout.setEnableLoadMore(false);
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {

    }

    @Override
    public String getPageTag() {
        return FragmentCheckout.class.getName();
    }

    private void initListener() {
        mAdapterGoodsInCheckout.setOnItemCheckedListener(new AdapterGoodsInCheckout.OnItemCheckedListener() {
            @Override
            public void onItemCheck(GoodsDetailBean item, boolean checked) {
                String number = BizUtil.getPureNumber(tvPriceTotal.getText().toString());
                item.setChecked(checked);
                if (checked) {
                    tvPriceTotal.setText("￥" + MathDecimalUtil.add(number, "" + MathDecimalUtil.mul("" + item.getCurSkuBean().getDiscountPrice(), "" + item.getSum())));
                } else {
                    tvPriceTotal.setText("￥" + MathDecimalUtil.sub(number, "" + MathDecimalUtil.mul("" + item.getCurSkuBean().getDiscountPrice(), "" + item.getSum())));
                }
                checkSelectedState();
            }
        });
        mAdapterGoodsInCheckout.setOnDeleteClickListener(new AdapterGoodsInCheckout.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(final GoodsDetailBean item) {
                DialogMakeSure dialog = new DialogMakeSure(mContext);
                dialog.getDialog("是否移除该商品?").show();
                dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
                    @Override
                    public void onSure(DialogInterface dialog, int which) {
                        //移除商品
                        mGoodsInOrderList.remove(item);
                        notifyDataSetChange();

                        String number = BizUtil.getPureNumber(tvPriceTotal.getText().toString());
                        tvPriceTotal.setText("￥" + MathDecimalUtil.sub(number, "" + MathDecimalUtil.mul("" + item.getCurSkuBean().getDiscountPrice(), "" + item.getSum())));
                    }

                    @Override
                    public void onCancel(DialogInterface dialog, int which) {
                    }
                });
            }
        });
        mAdapterGoodsInCheckout.setOnItemEditTextChangedListener(new AdapterGoodsInCheckout.OnItemEditTextChangedListener() {
            @Override
            public void onEditTextAfterTextChanged(Editable editable, int position) {
                GoodsDetailBean item = mGoodsInOrderList.get(position);
                String discount = editable.toString();
                if (discount.equals(".")) {
                    return;
                }
                if (TextUtils.isEmpty(discount)) {
                    item.getCurSkuBean().setDiscountPrice(item.getCurSkuBean().getPrice());
                    return;
                }
                if (Float.parseFloat(discount) > item.getCurSkuBean().getPrice()) {
                    item.setNotValid(true);
                } else {
                    item.getCurSkuBean().setDiscountPrice(Float.parseFloat(discount));
                    item.setNotValid(false);
                }
            }
        });
    }


    private void notifyDataSetChange() {
        mAdapterGoodsInCheckout.notifyDataSetChanged();
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mGoodsInOrderList.size() == 0) {
            layoutEmpty.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            layoutEmpty.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void enterShowMode() {
        mRecyclerView.smoothScrollToPosition(0);
        if (checkAndSave()) {
            ToastUtils.showShort("请设置合理的优惠价格");
        } else {
            isEdit = false;
            ntb.setRightText("编辑");
            mAdapterGoodsInCheckout.setMode(AppConstant.GOODS_MODE_SHOW);
            layoutPriceTotal.setVisibility(View.VISIBLE);
            layoutAction.setVisibility(View.VISIBLE);
            ViewGroup.LayoutParams params = layoutRealBottom.getLayoutParams();
            params.height = ConvertUtils.dp2px(94);
            layoutRealBottom.setLayoutParams(params);
            tvAction.setText("立即下单");
            tvPriceTotal.setText("￥" + BizGoodsUtil.getTotalPrice(BizGoodsUtil.getSelectedList((ArrayList<GoodsDetailBean>) mGoodsInOrderList)));
        }
    }

    private void enterEditMode() {
        mRecyclerView.smoothScrollToPosition(0);
        isEdit = true;
        ntb.setRightText("保存");
        mAdapterGoodsInCheckout.setMode(AppConstant.GOODS_MODE_EDIT);
        layoutAction.setVisibility(View.GONE);
        layoutPriceTotal.setVisibility(View.GONE);
        ViewGroup.LayoutParams params = layoutRealBottom.getLayoutParams();
        params.height = ConvertUtils.dp2px(54);
        layoutRealBottom.setLayoutParams(params);
        tvAction.setText("删除");
    }

    private boolean checkAndSave() {
        KeyboardUtils.hideSoftInput(getActivity());
        boolean flag = false;
        for (int i = 0; i < mGoodsInOrderList.size(); i++) {
            GoodsDetailBean bean = mGoodsInOrderList.get(i);
            if (bean.isNotValid()) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    private void checkSelectedState() {
        boolean flag = true;
        for (GoodsDetailBean bean : mGoodsInOrderList) {
            if (!bean.isChecked()) {
                flag = false;
            }
        }
        chkAll.setChecked(flag);
    }

    private void clearCheckout() {
        mGoodsInOrderList.clear();
        notifyDataSetChange();
        tvPriceTotal.setText("￥0");
    }

    private void clearSelectItem() {
        final ArrayList<GoodsDetailBean> list = new ArrayList<>();
        for (GoodsDetailBean bean : mGoodsInOrderList) {
            if (bean.isChecked()) {
                list.add(bean);
            }
        }
        if (list.size() == 0) {
            ToastUtils.showShort("没选选中商品");
        } else {
            DialogMakeSure dialog = new DialogMakeSure(mContext);
            dialog.getDialog("是否移除这些商品?").show();
            dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
                @Override
                public void onSure(DialogInterface dialog, int which) {
                    //移除商品
                    mGoodsInOrderList.removeAll(list);
                    notifyDataSetChange();
                    tvPriceTotal.setText("￥" + BizGoodsUtil.getTotalPrice(BizGoodsUtil.getSelectedList((ArrayList<GoodsDetailBean>) mGoodsInOrderList)));
                    enterShowMode();
                }

                @Override
                public void onCancel(DialogInterface dialog, int which) {
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mEvent != null) {
            start(FragmentSearch.newInstance(AppConstant.SEARCH_GOODS, AppConstant.GOODS_SELECT_IN_CHECKOUT, null, mEvent.getBarcode()));
            mEvent = null;
        }
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (flagToHome) {
            tvAction.postDelayed(new Runnable() {
                @Override
                public void run() {
                    pop();
                }
            }, 200);
        }
    }

    private void popCheckout() {
        if (mGoodsInOrderList.size() == 0) {
            pop();
        } else {
            final DialogLbCommon dialogLbCommon = DialogLbCommon.getDialogLbCommon(AppConstant.DIALOG_COMMON_CHOOSE, "确定退出收银台吗？", "点错啦", "确定");
            dialogLbCommon.show(getFragmentManager(),getPageTag());
            dialogLbCommon.setOnTwoButtonClickListener(new DialogLbCommon.OnTwoButtonClickListener() {
                @Override
                public void onLeftClick() {
                    dialogLbCommon.dismiss();
                }

                @Override
                public void onRightClick() {
                    dialogLbCommon.dismiss();
                    pop();
                }
            });
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        popCheckout();
        return true;
    }

    @OnClick(R.id.image_left)
    void leftClick() {
        popCheckout();
    }

    @OnClick(R.id.tv_right)
    void rightClick() {
        if (isEdit) {
            enterShowMode();
        } else {
            enterEditMode();
        }
    }

    @OnClick(R.id.chk_all)
    void checkAll() {
        if (chkAll.isChecked()) {
            mAdapterGoodsInCheckout.toggleCheck(true);
            tvPriceTotal.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tvPriceTotal.setText("￥" + BizGoodsUtil.getTotalPrice(BizGoodsUtil.getSelectedList((ArrayList<GoodsDetailBean>) mGoodsInOrderList)));
                }
            }, 200);
        } else {
            mAdapterGoodsInCheckout.toggleCheck(false);
            tvPriceTotal.setText("￥" + 0);
        }
    }


    @OnClick(R.id.layout_add_goods)
    void addGoods() {
        start(FragmentSelectGoods.newInstance(AppConstant.GOODS_SELECT_IN_CHECKOUT));
    }

    @OnClick(R.id.layout_scan)
    void scan() {
        Intent intent = new Intent(mContext, ScanSmallActivity.class);
        intent.putExtra(AppConstant.SCAN_MODE, AppConstant.SCAN_RETURN_GOODS);
        intent.putExtra(AppConstant.SCAN_FROM, AppConstant.SCAN_FROM_CHECKOUT);
        startActivity(intent);
    }

    @OnClick(R.id.tv_do_order)
    void doOrder() {
        if (!ClickUtil.isFastDoubleClick()) {
            if (isEdit) {
                clearSelectItem();
            } else {
                List selectedList = BizGoodsUtil.getSelectedList((ArrayList<GoodsDetailBean>) mGoodsInOrderList);
                if (selectedList.size() == 0) {
                    ToastUtils.showShort("请选择商品");
                } else {
                    sendRequestConfirmBuyOrder();
                }
            }
        }
    }

    //确认订单信息
    private void sendRequestConfirmBuyOrder() {
        RequestBody body = getRequestBody();
        if (body != null) {
            SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

                @Override
                public void onNext(BaseResponse response) {
                    if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                        JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                        start(FragmentSureOrder.newInstance(jsonObject.toString()));
                    } else {
                        ToastUtils.showShort(response.getMessage());
                    }
                }
            };
            SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
                @Override
                public void onSessionOutOfDate() {

                }

                @Override
                public void onError(String error) {
                    ToastUtils.showShort("确认订单失败:" + error);
                }
            };
            ApiMethodGuide.confirmBuyOrder(new SimpleLbObserver(listener, errorListener), body, this, FragmentEvent.DESTROY_VIEW);
        }
    }

    private RequestBody getRequestBody() {
        ConfirmOrderBean bean = new ConfirmOrderBean();
        ArrayList<GoodsDetailBean> selectedList = BizGoodsUtil.getSelectedList((ArrayList<GoodsDetailBean>) mGoodsInOrderList);
        bean.setProductList(getCommitGoodsList(selectedList));
        String json = JsonUtil.getGson().toJson(bean);
        return RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), json);
    }

    /**
     * 提交的goods数据
     *
     * @return
     */
    private List<CommitGoodsBean> getCommitGoodsList(ArrayList<GoodsDetailBean> selectList) {
        List<CommitGoodsBean> list = new ArrayList<>();
        for (GoodsDetailBean bean : selectList) {
            CommitGoodsBean commitGoodsBean = new CommitGoodsBean();
            commitGoodsBean.setProductCode(bean.getProductCode());
            commitGoodsBean.setProductSum(bean.getSum());
            commitGoodsBean.setSkuCode(bean.getCurSkuBean().getSkuCode());
            commitGoodsBean.setDiscountPrice("" + bean.getCurSkuBean().getDiscountPrice());
            list.add(commitGoodsBean);
        }
        return list;
    }


    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onSearchBarcode(SearchBarcodeCheckoutEvent event) {
        if (isStateSaved()) {
            mEvent = event;
        } else {
            start(FragmentSearch.newInstance(AppConstant.SEARCH_GOODS, AppConstant.GOODS_SELECT_IN_CHECKOUT, null, event.getBarcode()));
        }
    }

    /**
     * 选中的商品
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getSelectedGoods(SelectGoodsSkuEvent event) {
        FragmentCheckout fragment = findFragment(FragmentCheckout.class);
        if (fragment != null) {
            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    popTo(FragmentCheckout.class, false);
                }
            }, 200);
        }
        GoodsDetailBean goodsDetailBean = event.getGoodsDetailBean();
        goodsDetailBean.setChecked(true);
        boolean flag = false;
        for (int i = 0; i < mGoodsInOrderList.size(); i++) {
            GoodsDetailBean bean = mGoodsInOrderList.get(i);
            if (goodsDetailBean.getCurSkuBean().getSkuCode().equals(bean.getCurSkuBean().getSkuCode())) {
                goodsDetailBean.setSum(goodsDetailBean.getSum() + bean.getSum());
                mGoodsInOrderList.set(i, goodsDetailBean);
                flag = true;
            }
        }
        if (!flag) {
            mGoodsInOrderList.add(goodsDetailBean);
        }
        notifyDataSetChange();
        mRecyclerView.smoothScrollToPosition(mGoodsInOrderList.size() - 1);
        checkSelectedState();
        tvPriceTotal.setText("￥" + BizGoodsUtil.getTotalPrice(BizGoodsUtil.getSelectedList((ArrayList<GoodsDetailBean>) mGoodsInOrderList)));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void goHome(GoHomeEvent event) {
        flagToHome = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void clearCheckout(PaySuccessEvent event) {
        clearCheckout();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void clearCheckout(GiveupPayEvent event) {
        clearCheckout();
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
